//
//  ImageEnarge.m
//  ExcellentHome
//
//  Created by Andy on 16/6/3.
//  Copyright © 2016年 陈区. All rights reserved.
//
#import "ImageEnarge.h"
#include <CommonCrypto/CommonCrypto.h>
#import <UIImageView+WebCache.h>
#import "UIImageView+SEGWebCache.h"

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

static inline CGFloat GetViewWidth (UIView *view) {
    return view.frame.size.width;
}
@interface ImageEnarge ()<UIScrollViewDelegate>
{
    UIView *bgView;
    UIImageView *imgView;
}
@end

@implementation ImageEnarge

-(void)imageEnarge:(NSString *)url{
    NSString *imageUrl = url;
    
    if (bgView) {
        //设置不隐藏，还原放大缩小，显示图片
        bgView.hidden = NO;
        imgView.frame = self.view.bounds;
        [imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")]];
        imgView.center = bgView.center;
    }
    else
        [self showBigImage:imageUrl];//创建视图并显示图片

}
/*
 * @param query 需要转译的URL 非json格式
 * @return 返回字典
 */
-(NSDictionary *)JsonStringToDict:(NSString *)jsonString{
    NSArray *array = [jsonString componentsSeparatedByString:@"%"];
    NSDictionary *dict = [NSDictionary new];
    if ([array count]>=2) {
        
        dict = [self dictionaryWithJsonString:jsonString];
    }else{
        dict = [self dictionaryFromQuery:jsonString usingEncoding:nil];
    }
    return dict;
}
/*
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSString *jsonStr = [NSString new];
    if ([[jsonString componentsSeparatedByString:@"%"] count]>=2) {
        jsonStr = [jsonString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    }else{
        jsonStr = jsonString;
    }
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    if(err) {
        return nil;
    }
    return dic;
}
/*
 * @param query 需要转译的URL 非json格式
 * @return 返回字典
 */
- (NSDictionary*)dictionaryFromQuery:(NSString*)query usingEncoding:(NSStringEncoding)encoding
{
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:query];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0]
                             stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString* value = [[kvPair objectAtIndex:1]
                               stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [pairs setObject:value forKey:key];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:pairs];
}

/*
* 字典转json
*/
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (BOOL)returenClickImageresult:(NSString *)requestString view:(UIView *)View imageView:(UIImageView *)imageView{
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    bgView = View;
    imgView = imageView;
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];

        if (bgView) {
            //设置不隐藏，还原放大缩小，显示图片
            bgView.hidden = NO;
            imgView.frame = self.view.bounds;
            [imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")]];
            imgView.center = bgView.center;
        }
        else
            [self showBigImage:imageUrl];//创建视图并显示图片

        return NO;
    }
    return YES;
}
-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景，使其背后内容不可操作
    bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgView.backgroundColor = [UIColor blackColor];
    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView];
    
    UITapGestureRecognizer *closeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeTapAction:)];
    [bgView addGestureRecognizer:closeTap];
    //创建显示图像视图
    imgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imgView.userInteractionEnabled = YES;
    [imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")]];
    [bgView addSubview:imgView];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.center = bgView.center;
    //添加捏合手势
    [imgView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
    
    
}

//关闭按钮
-(void)closeTapAction:(UIGestureRecognizer *)recognizer
{
    bgView.hidden = YES;
}


- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
{
    //缩放:设置缩放比例
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;
    if (recognizer.view.frame.size.width < self.view.frame.size.width ) {
        [UIView animateWithDuration:0.5 animations:^{
            recognizer.view.transform = CGAffineTransformIdentity;
        }];
        
    }
    
}



-(void)baseArrayImageEnarge:(NSArray *)picArray index:(NSString *)index{
    UIScrollView* bgView1 = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    bgView1.delegate = self;
    bgView1.showsHorizontalScrollIndicator = NO;
    bgView1.showsVerticalScrollIndicator = NO;
    bgView1.backgroundColor = [UIColor clearColor];
    bgView1.pagingEnabled = YES;
    bgView1.contentSize = CGSizeMake([picArray count] * CGRectGetWidth([UIScreen mainScreen].bounds), [UIScreen mainScreen].bounds.size.height);
    bgView1.contentOffset = CGPointMake([index integerValue] * CGRectGetWidth([UIScreen mainScreen].bounds), 0);
    [[[UIApplication sharedApplication] keyWindow] addSubview:bgView1];
    
    //菊花
    UIActivityIndicatorView* activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.frame = CGRectMake(([index integerValue] * CGRectGetWidth([UIScreen mainScreen].bounds)) + CGRectGetWidth([UIScreen mainScreen].bounds) / 2, (CGRectGetHeight([UIScreen mainScreen].bounds) - 20) / 2, 20, 20);
    [activityView startAnimating];
    [bgView1 addSubview:activityView];
    
    [bgView1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeTapButton:)]];
    
    [UIView animateWithDuration:0.5 animations:^{
        bgView1.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
    }];
    
    
    if ([picArray count] > 0)
    {
        if ([picArray count] == 1) //单图显示
        {
            UIImageView* picImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            picImageView.userInteractionEnabled = YES;
            
            @synchronized(picImageView)
            {
                [picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [picArray objectAtIndex:0]]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")] options:(SDWebImageRetryFailed)];
                
            }
            picImageView.contentMode = UIViewContentModeScaleAspectFit;
            [bgView1 addSubview:picImageView];
            //添加捏合手势
            [picImageView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
            
           //托动
//            UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
//            [panRecognizer setMinimumNumberOfTouches:1];
//            [panRecognizer setMaximumNumberOfTouches:1];
//            [picImageView addGestureRecognizer:panRecognizer];
        }
        else //多图显示
        {
            
            for (int i = 0; i < [picArray count]; i++)
            {
                //分页控件
                UIPageControl* pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(i * CGRectGetWidth(bgView1.bounds), [[UIScreen mainScreen] bounds].size.height - 30, [[UIScreen mainScreen] bounds].size.width, 20)];
                pageControl.userInteractionEnabled = YES;
                pageControl.numberOfPages = [picArray count];
                pageControl.currentPage = i;
                [bgView1 addSubview:pageControl];
                
                UIImageView* picImageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * CGRectGetWidth(bgView1.bounds), 0, CGRectGetWidth(bgView1.bounds), CGRectGetHeight(bgView1.bounds))];
                
                @synchronized(picImageView)
                {
                    [picImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [picArray objectAtIndex:i]]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")] options:(SDWebImageRetryFailed)];
                }
                picImageView.userInteractionEnabled = YES;
                picImageView.center = CGPointMake(i*CGRectGetWidth(bgView1.frame)+bgView1.center.x, bgView1.center.y);
                picImageView.contentMode = UIViewContentModeScaleAspectFit;
                //添加捏合手势
                [picImageView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
                //托动
//                UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
//                [panRecognizer setMinimumNumberOfTouches:1];
//                [panRecognizer setMaximumNumberOfTouches:1];
//                [picImageView addGestureRecognizer:panRecognizer];
                
                [bgView1 addSubview:picImageView];

            }
            
        }
        //关闭菊花
        for (UIActivityIndicatorView* activityView in bgView1.subviews) {
            if ([activityView isKindOfClass:[UIActivityIndicatorView class]]) {
                [activityView removeFromSuperview];
            }
        }
    }
}
-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;   //返回的就是已经改变的图片
}


- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translatedPoint = [recognizer translationInView:self.view];
    CGFloat x = recognizer.view.center.x + translatedPoint.x;
    CGFloat y = recognizer.view.center.y + translatedPoint.y;
    
    recognizer.view.center = CGPointMake(x, y);
  
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
}
//关闭图片显示窗口
- (void)closeTapButton:(UIGestureRecognizer*)recongnizer
{
    [[recongnizer view] removeFromSuperview];
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    [NSString stringWithFormat:@"%f", scrollView.contentOffset.x/CGRectGetWidth(self.view.bounds)]
//    for (UIImageView* picImageView in scrollView.subviews) {
//        if ([picImageView isKindOfClass:[UIImageView class]]) {
//            picImageView.frame = scrollView.bounds;
//        }
//    }
//}


@end
